// 云函数：registerUser —— 资料齐全后注册或补齐资料（幂等）并完成登录
const cloud = require('wx-server-sdk');

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const users = db.collection('users');

exports.main = async (event, context) => {
  const { OPENID: openid } = cloud.getWXContext();
  const { nickName, avatarFileID } = event || {};

  if (!openid) return { code: 500, msg: '获取用户OpenID失败' };
  if (!nickName || !avatarFileID) return { code: 400, msg: '缺少必要参数' };

  try {
    const now = new Date();
    const q = await users.where({ _openid: openid }).limit(1).get();

    // 已存在
    if (q.data && q.data.length > 0) {
      const user = q.data[0];
      const profileComplete = !!(user.authorized && user.nickName && user.avatarUrl);

      // 已注册且资料完整：直接返回
      if (profileComplete) {
        return { code: 0, msg: '已注册', data: { userInfo: user } };
      }

      // 未完善则补齐
      await users.doc(user._id).update({
        data: {
          nickName,
          avatarUrl: avatarFileID, // 存储 fileID
          authorized: true,
          lastLoginTime: now,
          updateTime: now
        }
      });
      const updated = await users.doc(user._id).get();
      return { code: 0, msg: '资料补充完成', data: { userInfo: updated.data } };
    }

    // 不存在则创建
    const newUser = {
      _openid: openid,
      nickName,
      avatarUrl: avatarFileID,
      authorized: true,
      createTime: now,
      lastLoginTime: now,
      // 业务字段初始化
      points: 0,
      total_study_time: 0,
      study_streak: 0
    };

    const addRes = await users.add({ data: newUser });
    const created = await users.doc(addRes._id).get();

    return { code: 0, msg: '注册成功', data: { userInfo: created.data } };
  } catch (error) {
    console.error('registerUser error:', error);
    return { code: 500, msg: '服务器内部错误', error: error.message };
  }
};